//
//  informationsController.m
//  HYPublicEdition
//
//  Created by apple on 2017/3/21.
//  Copyright © 2017年 弘扬公众版. All rights reserved.
//

#import "informationsController.h"
#import "HealthyBKCell.h"
#import "YYInfiniteLoopView.h"
#import "Config.h"
#import "HACursor.h"
#import "UIView+Extension.h"
#import "HATestView.h"
#import "HealthyBKCell.h"
#import "informationfirstCell.h"
#import "informationsharewebview.h"
#import "MJRefresh.h"
#import "WebViewController.h"
#define sentselectindex @"sentselectindex" //通知

static CGFloat const loopViewH = 125.0f;
@interface informationsController ()<UITableViewDelegate,UITableViewDataSource>{
    UIScrollView * titlescrollview;
    UIScrollView * mainscrolleview;
    
    YYInfiniteLoopView *_loopView;
//    UITableView * tableview ;
    HACursor *cursor;
    NSMutableArray *_urlArray;
}
@property (nonatomic, strong) NSMutableArray *titles;
//@property (nonatomic, strong) NSMutableArray *hidetype;
@property (nonatomic, strong) NSArray * healtypedic; // 健康圈标题字典
@property (nonatomic, strong) NSMutableArray *pageViews;
@property (nonatomic, strong) NSMutableArray * lsitarrays;
@property (nonatomic, assign) int selectindex;
@property (nonatomic, assign) int curPage;
    
@end

@implementation informationsController

- (void)viewDidLoad {
    _selectindex = 0;
    _curPage = 1;
    self.titles = [[NSMutableArray alloc] init];
    self.lsitarrays = [[NSMutableArray alloc] init];
    [self gethealthtype]; // 获取健康圈类型
//    [self createHACursor];
//    [self getScrollImage];
    
}
#pragma mark 获取健康圈类型
-(void)gethealthtype{
    
    [HTTPSTool GETRequestHidenHUDWithPath: XHGetHealthC cookie:nil params:nil progress:^(NSProgress * _Nonnull progress) {
    } success:^(NSDictionary * _Nonnull JSON) {
//        LRLog(@"%@", JSON);
   
        self.healtypedic = JSON[@"data"][@"list"];
        for (int i = 0; i < self.healtypedic.count; i++) {
            [self.titles addObject:[self.healtypedic objectAtIndex:i][@"title"]];
        }
        [self createHACursor]; // 创建框架
        [self getScrollImage];
        
        
    } failure:^(NSError * _Nonnull error) {
//        _loopView.autoPlayer = YES;
        
    }];


}

#pragma mark HACursor 仿网易的第三方
-(void)createHACursor{
    cursor = [[HACursor alloc]init];
    cursor.frame = CGRectMake(0, 0, self.view.width, 45);
    cursor.titles = self.titles;
    cursor.pageViews = [self createPageViews];
    //设置根滚动视图的高度
    cursor.rootScrollViewHeight = self.view.frame.size.height - 45;
    //默认值是白色
    cursor.titleNormalColor = [UIColor blackColor];
    //默认值是白色
    cursor.titleSelectedColor = XHConfigColor;
    cursor.showSortbutton = NO;
    //默认的最小值是5，小于默认值的话按默认值设置
    cursor.minFontSize = 6;
    //默认的最大值是25，小于默认值的话按默认值设置，大于默认值按设置的值处理
    //cursor.maxFontSize = 30;
    //cursor.isGraduallyChangFont = NO;
    //在isGraduallyChangFont为NO的时候，isGraduallyChangColor不会有效果
    cursor.isGraduallyChangColor = YES;
    [self.view addSubview:cursor];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectedIndex:) name:sentselectindex object:nil];

}

-(void)selectedIndex:(NSNotification *)notion{
//    NSLog(@"%@",notion.object);
    _selectindex = [notion.object intValue];
    UITableView * tableview = (UITableView *)[cursor.pageViews objectAtIndex:_selectindex];
//    [tableview.mj_header beginRefreshing];
    [self getScrollImage];
//   UITableView * tableview = (UITableView *)[cursor.pageViews objectAtIndex:_selectindex];
//    [tableview reloadData];
}
    
    
- (NSMutableArray *)createPageViews{
    NSMutableArray *pageViews = [NSMutableArray array];
    for (NSInteger i = 0; i < self.titles.count; i++) {
            UITableView* tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
            tableview.tag = i + 100;
            tableview.delegate = self;
            tableview.dataSource = self;
            tableview.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        
        tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [tableview.mj_header beginRefreshing];
            [self getScrollImage]; //下拉刷新
        }];
        tableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            [tableview.mj_footer beginRefreshing];
            [self refreshlist];
        }];

//        }
        [pageViews addObject:tableview];
        
    }
    return pageViews;
}
#pragma 轮播图创建
- (UIView *)createLoopView {
    if (_loopView) return _loopView;
    NSArray *imageArray = @[@"",
                            @"",
                            @""];
    NSArray *titleArray = @[@"",@"",@""];
    __weak typeof(self) weakSelf = self;
    _loopView = [YYInfiniteLoopView infiniteLoopViewWithImageUrls:imageArray titles:titleArray didSelectedImage:^(NSInteger index) {
        [weakSelf touchLoopViewEventWithIndex:index];
    }];
    _loopView.autoPlayer = NO;
    _loopView.placeholderImage = [UIImage imageNamed:@"ScrollImage.jpg"];
    _loopView.currentPageIndicatorColor = [UIColor whiteColor];
    _loopView.pageIndicatorColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.5f];
    _loopView.bgViewColor = [[UIColor blackColor] colorWithAlphaComponent:0.5f]; // 显示主题的蒙版
//    _loopView.hideTitleLabel = YES;
    _loopView.frame = (CGRect){CGPointZero, XHScreenWidth, loopViewH};
    return _loopView;
}
    
#pragma mark touch loopView event
- (void)touchLoopViewEventWithIndex:(NSInteger)index {
    NSString *title = _loopView.titles[index];
    NSString *urlString = _urlArray[index];
//    XHLog(@"urlString: %@", urlString)
    NSURL *url = [URLTool webURLStringWithPathString:urlString token:[UserDefaultsTool stringForKey:XHToken]];
    WebViewController *web = [[WebViewController alloc] init];
    web.title = title;
    web.url = url;
    [self.navigationController pushViewController:web animated:YES];
}
#pragma mark - scrollImage //获取轮播图片
- (void)getScrollImage {
    NSString * index = nil;
    _curPage = 1; // 初始化为一页
    [self.lsitarrays removeAllObjects];
    if (self.healtypedic.count !=0) {
        NSDictionary * dic = [self.healtypedic objectAtIndex:self.selectindex];
        index = [NSString stringWithFormat:@"%@",dic[@"id"]];
    }else{
       index =  [NSString stringWithFormat:@"%d",self.selectindex + 1];
    }
    NSDictionary * params = @{@"id":index,
                              @"curPage":@"1",
                              @"pageSize":@"10"};
    __unsafe_unretained informationsController *weakSelf = self;
    [HTTPSTool POSTRequestWithPath:XHGhealthCC_list_data params:params success:^(NSDictionary * _Nonnull JSON) {
//        NSLog(@"%@",JSON);
        self.lsitarrays = [[NSMutableArray alloc] initWithArray:JSON[@"data"][@"list1"]];
         [weakSelf setScrollImageWithDataArray:JSON[@"data"][@"list2"]];
           UITableView * tableview = (UITableView *)[cursor.pageViews objectAtIndex:_selectindex];
            [tableview reloadData];
        [tableview.mj_header endRefreshing];

    }];
}
// 下拉加载
-(void)refreshlist{
    NSString * index = nil;
    _curPage ++; // 刷新自增
    if (self.healtypedic.count !=0) {
        NSDictionary * dic = [self.healtypedic objectAtIndex:self.selectindex];
        index = [NSString stringWithFormat:@"%@",dic[@"id"]];
    }else{
        [NSString stringWithFormat:@"%d",self.selectindex + 1];
    }
    NSDictionary * params = @{@"id":index,
                              @"curPage":[NSString stringWithFormat:@"%d",_curPage],
                              @"pageSize":@"10"};
//    __unsafe_unretained informationsController *weakSelf = self;
    [HTTPSTool POSTRequestWithPath:XHGhealthCC_list_data params:params success:^(NSDictionary * _Nonnull JSON) {
//        NSLog(@"%@",JSON);
        NSArray * arrays = [[NSMutableArray alloc] initWithArray:JSON[@"data"][@"list1"]];
        for (int i = 0; i < arrays.count; i++) {
            [self.lsitarrays addObject:[arrays objectAtIndex:i]];
        }
//        [weakSelf setScrollImageWithDataArray:JSON[@"data"][@"list2"]];
        UITableView * tableview = (UITableView *)[cursor.pageViews objectAtIndex:_selectindex];
        
        [tableview reloadData];
        [tableview.mj_footer endRefreshing];
    }];

}
- (void)setScrollImageWithDataArray:(NSArray *)dataArray {
    if (!dataArray.count) return ;
    // 轮播图处理
    NSMutableArray *imageArrayM = [NSMutableArray arrayWithCapacity:dataArray.count];
    NSMutableArray *titleArrayM = [NSMutableArray arrayWithCapacity:dataArray.count];
    _urlArray = [NSMutableArray arrayWithCapacity:dataArray.count];
    for (NSDictionary *dataDict in dataArray) {
        NSURL *imageUrl = [URLTool imageURLStringWithPathString:dataDict[@"image"]];
        [imageArrayM addObject:[imageUrl absoluteString]];
        [titleArrayM addObject:dataDict[@"title"]];
        [_urlArray addObject:dataDict[@"url"]];
    }
    _loopView.titles = titleArrayM;
    _loopView.imageUrls = imageArrayM;
    _loopView.autoPlayer = YES;
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:sentselectindex  object:nil];
}
    
#pragma mark scrolleview 代理

    
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

    
    
#pragma tableview 代理
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
     NSDictionary * dic = [self.healtypedic objectAtIndex:(int)self.selectindex];
    if ([dic[@"sflb"] intValue]  == 1) {
    
        return self.lsitarrays.count + 1;
    }else{
        return self.lsitarrays.count;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary * dic = [self.healtypedic objectAtIndex:(int)self.selectindex];
    if ([dic[@"sflb"] intValue]  == 1) { // 轮播 (1 有轮播图 0 没有轮播图)
        if (indexPath.row == 0) {
            static NSString * inderstr = @"cells";
            UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:inderstr];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:inderstr];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            [_loopView removeFromSuperview];
            [cell addSubview:[self createLoopView]];
            return cell;
        }else{
            static NSString * inderstr = @"cell";
            informationfirstCell * cell = [tableView dequeueReusableCellWithIdentifier:inderstr];
            if (cell == nil) {
                cell = [[[NSBundle mainBundle] loadNibNamed:@"informationfirstCell" owner:nil options:nil] firstObject];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            //个数至少为一个不能为零
            if (self.lsitarrays.count != 0) {
                NSDictionary * dic = [self.lsitarrays objectAtIndex:indexPath.row - 1];
                [cell.iconimage downloadImageWithURLString: dic[@"image"]  placeholderString:@"jkjy.png"];
                cell.timelabel.text = dic[@"createDate"];
                cell.personlabel.text = dic[@"description"];
                cell._label.text = dic[@"title"];
            }
           
            return cell;
        }
    }else{
        static NSString * inderstr = @"cell";
        informationfirstCell * cell = [tableView dequeueReusableCellWithIdentifier:inderstr];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"informationfirstCell" owner:nil options:nil] firstObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
    //限制数组以防发生越界（至少为1个）
        if (self.lsitarrays.count != 0) {
            NSDictionary * dic = [self.lsitarrays objectAtIndex:indexPath.row];
            [cell.iconimage downloadImageWithURLString: dic[@"image"]  placeholderString:@"jkjy.png"];
            cell.titlelabel.text = dic[@"title"];
            cell.timelabel.text = dic[@"createDate"];
            cell.personlabel.text = dic[@"description"];
            cell._label.text = dic[@"title"];

        }
              return cell;

    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary * dic = [self.healtypedic objectAtIndex:(int)self.selectindex];
    if ([dic[@"sflb"] intValue]  == 1) { // 轮播 (1 有轮播图 0 没有轮播图)
        switch (indexPath.row) {
            case 0:
                
                break;
            default:{
                NSDictionary * dic = [self.lsitarrays objectAtIndex:indexPath.row - 1];
                informationsharewebview * inforwebview = [[informationsharewebview alloc] init];
                inforwebview.hidesBottomBarWhenPushed = YES;
                inforwebview.url = dic[@"url"];
                inforwebview.title = dic[@"title"];
                inforwebview.text = dic[@"description"];
                [self.navigationController pushViewController:inforwebview animated:YES];
            }
                break;
        }
    }else{
        NSDictionary * dic = [self.lsitarrays objectAtIndex:indexPath.row];
        informationsharewebview * inforwebview = [[informationsharewebview alloc] init];
        inforwebview.hidesBottomBarWhenPushed = YES;
        inforwebview.url = dic[@"url"];
        inforwebview.title = dic[@"title"];
        inforwebview.text = dic[@"description"];
        [self.navigationController pushViewController:inforwebview animated:YES];
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary * dic = [self.healtypedic objectAtIndex:(int)self.selectindex];
    if ([dic[@"sflb"] intValue] == 1) {
       switch (indexPath.row) {
           case 0:
           return loopViewH;
           break;
        
           default:
           return 80;
           break;
       }
    }else{
        return 80;
    }
}
@end
